package cn.hx.admin.security;

import cn.hx.admin.entity.User;
import cn.hx.admin.util.RedisUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Component
public class AuthenticationTokenFilter extends OncePerRequestFilter {
    @Autowired
    RedisUtil<Object> redisUtil;

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        // 1、从参数中获取token，如果不存在token，直接放行即可！由Spring Security的过滤器进行校验！
        // System.out.println(request.getRequestURL());
        String token = request.getHeader("Authorization");
        if (token == null || "".equals(token)) {
            // System.out.println("不存在token，直接放行");
            filterChain.doFilter(request, response);
            return;
        }

        // 2、然后将查询到的 User对象的相关信息封装到UsernamePasswordAuthenticationToken对象中，然后将该对象存储到Security的上下文对象中
        User user = (User) redisUtil.get(token);
        if (user!=null) {
            UsernamePasswordAuthenticationToken authentication=new UsernamePasswordAuthenticationToken(user,null,user.getAuthorities());
            SecurityContextHolder.getContext().setAuthentication(authentication);
        }
        filterChain.doFilter(request, response);
    }

}
